package ua.kharkov.khpi.tarasenko.bach.core.user;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

import sun.misc.BASE64Encoder;
import ua.kharkov.khpi.tarasenko.bach.core.EShopException;

/**
 * Provides password encription.
 * 
 * @author oleksandr
 *
 */
public class PasswordEncryptor {
	private static final Logger log = Logger.getLogger(PasswordEncryptor.class);
	private static final String ALGORYTHM = "MD5";

	public String encode(String password) throws EShopException {
		byte[] data = new byte[0];
		try {
			MessageDigest m = MessageDigest.getInstance(ALGORYTHM);
			m.update(password.getBytes());
			data = m.digest();
			if (log.isTraceEnabled()) {
				log.trace("Password successfuly crypted.");
			}
		} catch (NoSuchAlgorithmException e) {
			throw new EShopException("Can't crypt password!", e);
		}
		
		/**
		 * TODO read about this shit
		 */
		return new BASE64Encoder().encode(data);
	}
}
